document.addEventListener('DOMContentLoaded', init);

function init() {
   // 全屏控制
  document.getElementById('fullscreen-btn').addEventListener('click', () => {
    const selector = document.getElementById('month-selector');
    const monthValue = selector.value;
    
    // 发送打开全屏请求
    chrome.runtime.sendMessage({
      action: "openFullscreen",
      month: monthValue
    });
  });

  // 初始化月份选择器
  initMonthSelector();
  
  // 加载当前月数据
  loadData(new Date());
}

function initMonthSelector() {
  const selector = document.getElementById('month-selector');
  const months = [];
  const now = new Date();
  
  // 生成最近12个月选项
  for (let i = -6; i <= 6; i++) {
    const date = new Date(now.getFullYear(), now.getMonth() + i, 1);
    months.push(date);
  }

  months.forEach(date => {
    const option = document.createElement('option');
    option.value = date.getTime();
    option.textContent = `${date.getFullYear()}年${date.getMonth() + 1}月`;
    if (date.getMonth() === now.getMonth() && date.getFullYear() === now.getFullYear()) {
      option.selected = true;
    }
    selector.appendChild(option);
  });

  // 月份切换事件
  selector.addEventListener('change', (e) => {
    loadData(new Date(parseInt(e.target.value)));
  });
}

function loadData(targetMonth) {
  const year = targetMonth.getFullYear();
  const month = targetMonth.getMonth();
  
  // 计算当月时间范围
  const startTime = new Date(year, month, 1).getTime();
  const endTime = new Date(year, month + 1, 0).getTime();
  
  // 发送历史记录请求
  chrome.runtime.sendMessage({
    action: "getHistory",
    startTime,
    endTime
  }, (response) => {
    if (response && response.dailyHours) {
      renderChart(response.dailyHours, targetMonth);
      calculateStats(response.dailyHours, targetMonth);
    }
  });
}

function renderChart(dailyHours, targetMonth) {
  const chartDom = document.getElementById('chart');
  const chart = echarts.init(chartDom);
  
  // 生成当月所有日期（含空白日）
  const daysInMonth = new Date(
    targetMonth.getFullYear(), 
    targetMonth.getMonth() + 1, 
    0
  ).getDate();
  
  const fullData = [];
  for (let day = 1; day <= daysInMonth; day++) {
    const dateStr = `${targetMonth.getFullYear()}-${(targetMonth.getMonth()+1).toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    const existing = dailyHours.find(d => d.date === dateStr);
    fullData.push(existing || {
      date: dateStr,
      hours: 0,
      isWeekend: new Date(dateStr).getDay() % 6 === 0
    });
  }

  // 图表配置[12,13](@ref)
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params) => {
        const data = params[0];
        const date = new Date(data.name);
        return `
          <div>${date.getMonth()+1}月${date.getDate()}日 (${['日','一','二','三','四','五','六'][date.getDay()]})</div>
          <div>工作时长: <b>${data.value} 小时</b></div>
          ${data.value >= 8 ? '<span style="color:#52c41a">✓ 达标</span>' : '<span style="color:#f5222d">✗ 未达标</span>'}
        `;
      }
    },
    xAxis: {
      type: 'category',
      data: fullData.map(d => d.date),
      axisLabel: {
        formatter: value => new Date(value).getDate()
      }
    },
    yAxis: {
      type: 'value',
      name: '工作时长 (小时)',
      max: 12
    },
    series: [{
      data: fullData.map(d => ({
        value: d.hours,
        itemStyle: {
          color: d.isWeekend ? '#91cc75' : 
                 d.hours >= 8 ? '#5470c6' : 
                 d.hours > 0 ? '#ffbab0' : '#eee'
        }
      })),
      type: 'bar',
      barWidth: '60%'
    }],
    dataZoom: [{
      type: 'inside',
      start: 0,
      end: 100
    }]
  };

  chart.setOption(option);
  
  // 窗口大小变化时重绘图表
  window.addEventListener('resize', () => chart.resize());
}

function calculateStats(dailyHours, targetMonth) {
  // 计算工作日天数（排除周末）[15](@ref)
  const year = targetMonth.getFullYear();
  const month = targetMonth.getMonth();
  const start = new Date(year, month, 1);
  const end = new Date(year, month + 1, 0);
  
  let workDays = 0;
  for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) {
    if (d.getDay() !== 0 && d.getDay() !== 6) workDays++;
  }
  
  const expectedHours = workDays * 8;
  const actualHours = dailyHours.reduce((sum, day) => sum + day.hours, 0);
  const completion = Math.min(100, Math.round((actualHours / expectedHours) * 100));
  
  // 更新UI
  document.getElementById('expected-hours').textContent = `${expectedHours} 小时`;
  document.getElementById('actual-hours').textContent = `${actualHours.toFixed(1)} 小时`;
  document.getElementById('completion').textContent = `${completion}%`;
  document.getElementById('completion').style.color = 
    completion >= 100 ? '#52c41a' : completion > 80 ? '#faad14' : '#f5222d';
}